//
//  UITableView_runtime.swift
//  AJiTai
//
//  Created by 周博 on 2020/6/16.
//  Copyright © 2020 BO ZHOU. All rights reserved.
//

import UIKit
import MJRefresh

// 防止在交换的layoutSubviews方法中设置frame 导致循环调用layoutSubviews

private var UITableView_headerRefreshBlock_key: String = "UITableView_headerRefreshBlock_key"

private var UITableView_footerRefreshBlock_key: String = "UITableView_footerRefreshBlock_key"




public extension UITableView {

    override open class func initRunTime() {

        // 因为不太好交换init(frame:) 和 init(coder:)方法, 所以取巧, 交换setDelegate方法
        exchange(originalSelector: #selector(setter: delegate), swizzledSelector: #selector(exchange_delegate(delegate:)))
    }

    @objc func exchange_delegate(delegate: Any) {

        exchange_delegate(delegate: delegate)

        if #available(iOS 11.0, *) {
            // 遇到navigationBar自动向下偏移
            // 设置这个属性在执行转场动画的时候可能有点问题, 这个属性设置.always之后, 如果tableview不可偏移, 系统也会自动设置像素大约为10 的内边距
            contentInsetAdjustmentBehavior = .never
        } else {
            /// Fallback on earlier versions
        }

        keyboardDismissMode = .onDrag

        /// 关闭Self-Sizing
//        estimatedRowHeight = 0
        estimatedSectionHeaderHeight = 0
        estimatedSectionFooterHeight = 0

        /// tableview默认自动计算高度
//        estimatedRowHeight = 40
//        rowHeight = UITableView.automaticDimension
    }





    // MARK: - 扩展属性

    /** 下拉刷新 */
    var headerRefreshBlock: (() -> Void)? {
        get {
            if let headerRefreshBlock = objc_getAssociatedObject(self, &UITableView_headerRefreshBlock_key) as? () -> Void {
                return headerRefreshBlock
            } else {
                return nil
            }
        }
        set {
            objc_setAssociatedObject(self, &UITableView_headerRefreshBlock_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

            if headerRefreshBlock != nil {
                mj_header = MJRefreshNormalHeader(refreshingBlock: headerRefreshBlock!)
                
                // 修改刷新信息label的颜色
                if let label = mj_header?.value(forKeyPath: "lastUpdatedTimeLabel") as? UILabel {
                    label.textColor = UIColor.white.withAlphaComponent(0.8)
                }
                if let label = mj_header?.value(forKeyPath: "_stateLabel") as? UILabel {
                    label.textColor = UIColor.white.withAlphaComponent(0.8)
                }
                
                /// 导航栏下隐藏MJ_header
                mj_header!.isAutomaticallyChangeAlpha = true
            } else {
                mj_header = nil
                print("设置mj_header为nil")
            }
        }
    }
    
    /** 上拉加载更多 */
    var footerRefreshBlock: (() -> Void)? {
        get {
            if let footerRefreshBlock = objc_getAssociatedObject(self, &UITableView_footerRefreshBlock_key) as? () -> Void {
                return footerRefreshBlock
            } else {
                return nil
            }
        }
        set {
            objc_setAssociatedObject(self, &UITableView_footerRefreshBlock_key, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)

            if footerRefreshBlock != nil {
                mj_footer = MJRefreshBackNormalFooter(refreshingBlock: footerRefreshBlock!)
                
            } else {
                mj_footer = nil
            }
        }
    }
    
    /** 设置刷新的title */
    var headerRefreshTitle: String? {
        get {
            return nil
        } set {
            
            (mj_header as? MJRefreshStateHeader)?.setTitle(newValue ?? "", for: .idle)
        }
    }
}
